package com.dlc.felear.xiaoensale.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.TempCookingMenuList;
import com.dlc.felear.xiaoensale.utils.HttpApi;
import com.dlc.felear.xiaoensale.utils.JasyptUtil;
import com.dlc.felear.xiaoensale.utils.MenuPicUtil;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class CookingMenuMangerHelper {
    private static String TAG = "CookingMenuMangerHelper";
    private static CookingMenuMangerHelper instance;
    private Context context;
    private CookingMenuDao cookingMenuDao;
    private HashMap<String, CookingMenu> tempList;
    public static final String ALL = "Q";
    public static final String A = "A";
    public static final String B = "B";
    public static final String C = "C";
    public static final String D = "D";
    public static final String E = "E";
    public static final String F = "F";
    public static final String G = "G";
    public static final String H = "H";
    public static final String QITALEI = Constant.ZHENGCAI;
    private List<String> catLists = new ArrayList<>();
    private List<String> catListNames = new ArrayList<>();
    private HashMap<String, HashMap<String, CookingMenu>> catMaps = new HashMap<>();
    private MenuFoodMaterialDao menuFoodMaterialDao;
    private HashMap<String, String> normalMenus = new HashMap<>();
    private HashMap<String, String> menusFl = new HashMap<>();
    private List<String> tempMenuIds = new ArrayList<>();
    private HashMap<String, Integer> mutilMenus = new HashMap<>();
    private ThreadPoolExecutorHelper threadPoolExecutorHelper;
    private int function = 0;
    private OperatorDao operatorDao;
    private MenuFoodMaterialDao foodMaterialDao;
    private HashMap<String, MenuFoodMaterial> stdMenuFoodMaterialList = new HashMap<>();

    private CookingMenuMangerHelper(Context context, CookingMenuDao cookingMenuDao) {
        this.context = context;
        this.cookingMenuDao = cookingMenuDao;
        tempList = new HashMap<>();
        foodMaterialDao=new MenuFoodMaterialDao(context);
        menuFoodMaterialDao = new MenuFoodMaterialDao(context);
        threadPoolExecutorHelper = ThreadPoolExecutorHelper.getInstance();
        function = Session.getSession().getInt(Constant.DEVICE_FUNTION, 0);
        operatorDao=new OperatorDao(context);
        initData();
        queryData();
        initStdMenuFoodMaterial();
    }

    public static CookingMenuMangerHelper getInstance(Context context, CookingMenuDao cookingMenuDao) {
        if (instance == null) {
            synchronized (CookingMenuMangerHelper.class) {
                if (instance == null) {
                    instance = new CookingMenuMangerHelper(context, cookingMenuDao);
                }
            }
        }
        return instance;
    }

    private void initData() {
        catLists.add("AX");
        catLists.add("AY");
        catLists.add("AZ");
        catLists.add("BX");
        catLists.add("BY");
        catLists.add("BZ");
        catLists.add("CX");
        catLists.add("CY");
        catLists.add("CZ");
        catLists.add("DX");
        catLists.add("DY");
        catLists.add("DZ");
        catLists.add("EX");
        catLists.add("EY");
        catLists.add("EZ");
        catLists.add("FX");
        catLists.add("FY");
        catLists.add("FZ");
        catLists.add("GX");
        catLists.add("GY");
        catLists.add("GZ");
        catLists.add("HX");
        catLists.add("HY");
        catLists.add("HZ");
        for (String name : catLists) {
            menusFl.put(name, name);
        }
        catListNames.add(getCatNameByRes(R.string.quanbu));
        catListNames.add(getCatNameByRes(R.string.yezilei));
        catListNames.add(getCatNameByRes(R.string.genjinglei));
        catListNames.add(getCatNameByRes(R.string.guaguolei));
        catListNames.add(getCatNameByRes(R.string.rou));
        catListNames.add(getCatNameByRes(R.string.yu));
        catListNames.add(getCatNameByRes(R.string.douzhipin));
        catListNames.add(getCatNameByRes(R.string.yanzhipin));
        catListNames.add(getCatNameByRes(R.string.qitalei));
        catListNames.add(getCatNameByRes(R.string.jinricaipin));
        saveCatCooking();
    }

    /**
     * 获取今日菜谱
     *
     * @return
     */
    public List<CookingMenu> getJrcpMenuList() {
        Log.e(TAG, "今日菜谱:" + tempList.size() + " data:" + JsonHelper.toJson(tempList));
        if (tempList == null || tempList.isEmpty()) {
            queryData();
        }
        return new ArrayList<>(tempList.values());
    }

    /**
     * 处理在线获取数据
     *
     * @param data
     */
    private void handleTempData(List<TempCookingMenuList.DataDTO> data) {
        if (data != null && !data.isEmpty()) {
            tempList.clear();
        }
        tempMenuIds.clear();
        Log.e(TAG, "今日菜谱:" + data.size() + "个");
//        ArrayList<CookingMenu> tempListData = new ArrayList<>();
        for (TempCookingMenuList.DataDTO dataDTO : data) {
            MenuPicUtil.getInstance(context).addDownLoadPicTask(dataDTO.getFoodmenuName(), dataDTO.getPic(), 0);
            tempMenuIds.add(dataDTO.getFoodmenuName() + "_" + dataDTO.getCategory());
            List<CookingMenu> list = cookingMenuDao.queryForName(dataDTO.getFoodmenuName());
            if (list != null && !list.isEmpty()) {
                for (CookingMenu c : list) {
                    c.setCategory(dataDTO.getCategory());
                    c.setMachineModoel(c.getMachineModoel());
                    saveJrcp(c);
//                    tempListData.add(c);
                }
            } else {
                downMenu(dataDTO.getFoodmenuName(), dataDTO.getId(), dataDTO.getMachineModoel(), dataDTO.getPic());
                Log.e(TAG, "在本地没有找到对应菜谱:" + dataDTO.getFoodmenuName() + " data:" + JsonHelper.toJson(getCookingMenuLikeName(dataDTO.getFoodmenuName(), "M400", 3)));
            }
        }
        Log.e(TAG, "今日菜谱缓存:" + JsonHelper.toJson(tempList));
    }

    /**
     * 更新
     *
     * @param id
     * @param model
     */
    private void downMenu(String anme, String id, String model, String pic) {
        Log.e(TAG, "");
        SendData.sendUpdateMenuInfo(id, model, context, cookingMenuDao);
    }

    /**
     * 初始化分类菜谱
     */
    public void saveCatCooking() {
        threadPoolExecutorHelper.getScheduledThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    handleMutilMenu(null, 0);
                    List<CookingMenu> tempList = cookingMenuDao.queryForAll();
                    Log.e(TAG, "tempList:" + tempList.size());
                    for (CookingMenu cookingMenu : tempList) {
                        handleMutilMenu(cookingMenu, 1);
//                        Log.e(TAG, "menuFoodMaterials:" + JsonHelper.toJson(menuFoodMaterialDao.queryForAllByCId(cookingMenu.getId())));
                        if (cookingMenu.getName().contains(A)) {
                            saveMenuData(A, cookingMenu);
                        } else if (cookingMenu.getName().contains(B)) {
                            saveMenuData(B, cookingMenu);
                        } else if (cookingMenu.getName().contains(C)) {
                            saveMenuData(C, cookingMenu);
                        } else if (cookingMenu.getName().contains(D)) {
                            saveMenuData(D, cookingMenu);
                        } else if (cookingMenu.getName().contains(E)) {
                            saveMenuData(E, cookingMenu);
                        } else if (cookingMenu.getName().contains(F)) {
                            saveMenuData(F, cookingMenu);
                        } else if (cookingMenu.getName().contains(G)) {
                            saveMenuData(G, cookingMenu);
                        } else if (cookingMenu.getName().contains(H)) {
                            saveMenuData(H, cookingMenu);
                        }
                    }
                    handleMutilMenu(null, 2);
                } catch (Exception e) {
                    Log.e(TAG, "saveCatCooking:" + e.getMessage());
                }
            }
        });

    }

    private void handleMutilMenu(CookingMenu cookingMenu, int flag) {
        if (flag == 0) {
            mutilMenus.clear();
            return;
        }
        if (flag == 2) {
            for (String tt : mutilMenus.keySet()) {
                int times = mutilMenus.get(tt);
                if (times > 1) {
                    String[] arr = tt.split("_");
                    if (arr.length == 3) {
//                        cookingMenuDao.deleteMenu(arr[0], arr[1], arr[2]);
                        Log.e(TAG, "菜谱重复需要删除");
                    }

                }
            }
            return;
        }
        if (TextUtils.equals(cookingMenu.getMachineModoel(), Constant.ZHENGCAI)) {
            return;
        }
        String key = cookingMenu.getName()
                + "_" + cookingMenu.getMachineModoel() + "_" + cookingMenu.getSpecification();
        if (!mutilMenus.containsKey(key)) {
            mutilMenus.put(key, 1);
        } else {
            mutilMenus.put(key, (mutilMenus.get(key) + 1));
        }
    }


    /**
     * 保存其他菜谱
     *
     * @param cookingMenu
     */
    private void saveQtcp(CookingMenu cookingMenu) {
        if (!catMaps.containsKey(QITALEI)) {
            catMaps.put(QITALEI, new HashMap<String, CookingMenu>());
        }
        HashMap<String, CookingMenu> tempList = catMaps.get(QITALEI);
        tempList.put(cookingMenu.getId(), cookingMenu);
        catMaps.put(QITALEI, tempList);
    }

    /**
     * 分类保存菜谱
     *
     * @param tag
     * @param cookingMenu
     */
    private void saveMenuData(String tag, CookingMenu cookingMenu) {
        if (!isHasCat(cookingMenu.getName())) {
            Log.e(TAG, "saveCatCooking 菜谱名不含分类字母 name:" + cookingMenu.getName());
            return;
        }
        if (TextUtils.isEmpty(cookingMenu.getParam1()) && function == 0) {
            Log.e(TAG, "菜谱没有公式 name:" + cookingMenu.getName());
            return;
        }
        if (TextUtils.equals(cookingMenu.getMachineModoel(), Constant.ZHENGCAI) && function == 0) {
            Log.e(TAG, "非炒菜机类型:" + cookingMenu.getName() + " id:" + cookingMenu.getMachineModoel());
            return;
        }
        List<Operator>  tempListOp=operatorDao.queryForAllByMID(cookingMenu.getId());
        if (tempListOp==null || tempListOp.isEmpty()) {
            Log.e(TAG, "菜谱没有炒菜步骤:" + cookingMenu.getName());
            return;
        }
        saveAllMenu(cookingMenu);
        saveQtcp(cookingMenu);
        if (cookingMenu.getType() == Constant.MENU_NORMAL) {
            normalMenus.put(cookingMenu.getId(), cookingMenu.getId());
        }
        if (!catMaps.containsKey(tag)) {
            catMaps.put(tag, new HashMap<String, CookingMenu>());
        }
        HashMap<String, CookingMenu> tempList = catMaps.get(tag);
        tempList.put(cookingMenu.getId(), cookingMenu);
        catMaps.put(tag, tempList);
    }

    private void saveAllMenu(CookingMenu cookingMenu) {
        if (!catMaps.containsKey(ALL)) {
            catMaps.put(ALL, new HashMap<String, CookingMenu>());
        }
        HashMap<String, CookingMenu> tempList = catMaps.get(ALL);
        tempList.put(cookingMenu.getId(), cookingMenu);
        catMaps.put(ALL, tempList);
    }


    public List<String> getCatLists() {
        return catLists;
    }

    public List<String> getCatListNames() {

        return catListNames;
    }

    public void updateCookingMenu(CookingMenu cookingMenu) {
        if (cookingMenu.getName().contains(A)) {
            saveMenuData(A, cookingMenu);
        } else if (cookingMenu.getName().contains(B)) {
            saveMenuData(B, cookingMenu);
        } else if (cookingMenu.getName().contains(C)) {
            saveMenuData(C, cookingMenu);
        } else if (cookingMenu.getName().contains(D)) {
            saveMenuData(D, cookingMenu);
        } else if (cookingMenu.getName().contains(E)) {
            saveMenuData(E, cookingMenu);
        } else if (cookingMenu.getName().contains(F)) {
            saveMenuData(F, cookingMenu);
        } else if (cookingMenu.getName().contains(G)) {
            saveMenuData(G, cookingMenu);
        } else if (cookingMenu.getName().contains(H)) {
            saveMenuData(H, cookingMenu);
        }
        MenuPicUtil.getInstance(context).addDownLoadPicTask(cookingMenu.getName(), cookingMenu.getPic(), 0);
    }

    public List<String> getStdCatListNames() {
        List<String> tempList = new ArrayList<>();
        for (String name : catListNames) {
            if (TextUtils.equals(name, getCatNameByRes(R.string.jinricaipin))) {
                continue;
            }
            tempList.add(name);
        }
        return tempList;
    }

    public List<CookingMenu> getCookingMenuLikeName(String name, String deviceType, int level) {
        List<CookingMenu> tempList = new ArrayList<>();
        for (CookingMenu cookingMenu : getCatMenuList(context.getString(R.string.quanbu), deviceType, level)) {
            if (level == 3 && cookingMenu.getName().contains(name) && TextUtils.equals(cookingMenu.getLevel(), deviceType)) {
                tempList.add(cookingMenu);
            } else if (cookingMenu.getName().contains(name) && TextUtils.equals(cookingMenu.getLevel(), deviceType)
                    && level != 3 && cookingMenu.getType() == level) {
                tempList.add(cookingMenu);
            }
        }
        return tempList;
    }

    public boolean isHasCat(String name) {
        boolean temp = false;
        if (!TextUtils.isEmpty(name) && name.length() > 2) {
            String ss = name.substring(name.length() - 2);
            if (menusFl.containsKey(ss)) {
                return true;
            }
        }
        return temp;
    }


    public void queryData() {
        Log.e(TAG, "onError:queryData");
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put("deviceId", APPDidUtil.getAppDid());
        String sign = JasyptUtil.getInstance().getSign(paramers);
        paramers.put("sign", sign);
        OkHttpManager.HttpPostJson(HttpApi.URL_CURRMENULIST, paramers, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "onError:" + e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "今日菜谱 onResponse:" + s);
                    TempCookingMenuList list = JsonHelper.parserJson(s, TempCookingMenuList.class);
                    Log.e(TAG, "list:" + JsonHelper.toJson(list.getData()));
                    if (list != null && list.getCode() == 1) {
                        if (list.getData() != null && !list.getData().isEmpty()) {
                            handleTempData(list.getData());
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }


    public List<CookingMenu> getCookingData(String deviceType, int level) {
        if (TextUtils.equals(deviceType, QITALEI)) {
            return getQtl(level);
        }
        return getCatMenuList(context.getString(R.string.quanbu), deviceType, level);
    }

    private List<CookingMenu> getQtl(int type) {
        ArrayList<CookingMenu> list = new ArrayList<>();
        if (catMaps.containsKey(QITALEI)) {
            for (CookingMenu cookingMenu : catMaps.get(QITALEI).values()) {
                list.add(cookingMenu);
            }
        }
        return list;
    }


    private String getCatNameByRes(int resId) {
        String tamp = context.getString(resId);
        return tamp;
    }

    public String changeValue(String catName) {
        String temp = "";
        if (TextUtils.equals(catName, getCatNameByRes(R.string.yezilei))) {
            temp = "A";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.genjinglei))) {
            temp = "B";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.guaguolei))) {
            temp = "C";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.rou))) {
            temp = "D";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.yu))) {
            temp = "E";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.douzhipin))) {
            temp = "F";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.yanzhipin))) {
            temp = "G";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.qitalei))) {
            temp = "H";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.quanbu))) {
            temp = "Q";
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.jinricaipin))) {
            temp = "S";
        }
        return temp;
    }


    public List<CookingMenu> getCatMenuList(String catName, String deviceType, int level) {
        initJrcp();
        List<CookingMenu> tempList = new ArrayList<>();
        if (level == 3) {
            return getCatMenuList(catName, deviceType);
        }
        for (CookingMenu cookingMenu : getCatMenuList(catName, deviceType)) {
            if (level == cookingMenu.getType()) {
                Log.e(TAG, "符合条件菜谱:level=" + level + " getType=" + cookingMenu.getType());
                tempList.add(cookingMenu);
            }
        }
        Log.e(TAG, "catName:" + catName + " deviceType:" + deviceType + " level=" + level + "data:" + tempList.size());
        return tempList;
    }

    private List<CookingMenu> getCatMenuList(String catName, String deviceType) {
        List<CookingMenu> tempList = new ArrayList<>();
        String key = changeValue(catName);
        if (catMaps.isEmpty()) {
            saveCatCooking();
        }
        if (catMaps.get(key) != null) {
            Log.e(TAG, "deviceType:" + deviceType + " key:" + key + " catMaps:" + catMaps.get(key).size());
        } else {
            Log.e(TAG, "deviceType:" + deviceType + " key:" + key + " catMaps:0");
        }
        if (TextUtils.equals(catName, getCatNameByRes(R.string.jinricaipin))) {
            return getJrcpMenuList();
        }
        if (TextUtils.equals(key, QITALEI)) {
            for (CookingMenu cookingMenu : catMaps.get(QITALEI).values()) {
                if (TextUtils.equals(key, ALL) && TextUtils.equals(cookingMenu.getMachineModoel(), deviceType)) {
                    tempList.add(cookingMenu);
                } else if (!TextUtils.equals(key, QITALEI) && cookingMenu.getName().contains(key)
                        && TextUtils.equals(cookingMenu.getMachineModoel(), deviceType)) {
                    tempList.add(cookingMenu);
                }
            }
        } else if (catMaps.containsKey(key) && catMaps.get(key) != null) {
            for (CookingMenu cookingMenu : catMaps.get(key).values()) {
                if (TextUtils.equals(cookingMenu.getMachineModoel(), deviceType)) {
                    tempList.add(cookingMenu);
                }
            }
        }
        if (TextUtils.equals(key, ALL) && tempList.isEmpty()) {
            saveCatCooking();
            return cookingMenuDao.queryForType(Constant.MENU_NORMAL);
        }
        return tempList;
    }

    private void initJrcp() {
        if (!tempList.isEmpty() || tempMenuIds.isEmpty()) {
            return;
        }
//        List<CookingMenu> tempListData = new ArrayList<>();
        for (String name : tempMenuIds) {
            String[] temArr = name.split("_");
            if (temArr == null || temArr.length != 2) {
                continue;
            }
            if (TextUtils.isEmpty(temArr[0]) || TextUtils.isEmpty(temArr[1])) {
                continue;
            }
            List<CookingMenu> list = cookingMenuDao.queryForName(temArr[0]);
            if (list != null && !list.isEmpty()) {
                for (CookingMenu c : list) {
                    c.setCategory(temArr[0]);
                    c.setMachineModoel(c.getMachineModoel());
                    saveJrcp(c);
                }
            }
        }
//        if (!tempListData.isEmpty()) {
//            this.tempList.clear();
//            this.tempList.addAll(tempListData);
//        }
    }

    private void saveJrcp(CookingMenu cookingMenu) {
        tempList.put(cookingMenu.getName() + cookingMenu.getMachineModoel(), cookingMenu);
    }

    public boolean ishashNolmalMenu(String menuName) {
        if (normalMenus.containsKey(menuName)) {
            return true;
        }
        return false;
    }

    public void removeMenuInfo(CookingMenu cookingMenu) {

    }

    public List<MenuFoodMaterial>  getStdMenuFoodMaterials(String name){
        List<MenuFoodMaterial> templist=new ArrayList<>();
        try {
            if(TextUtils.isEmpty(name)){
                return new ArrayList<>(stdMenuFoodMaterialList.values());
            }
            for(String key:stdMenuFoodMaterialList.keySet()){
                if(key.contains(name)){
                    templist.add(stdMenuFoodMaterialList.get(key));
                }
            }
        }catch (Exception e){
            Log.e(TAG,"getStdMenuFoodMaterials:"+e.getMessage());
        }
        return templist;
    }

    private void initStdMenuFoodMaterial(){
       try {
           final String deviceId=APPDidUtil.getAppDid();
           threadPoolExecutorHelper.getScheduledThreadPool().submit(new Runnable() {
               @Override
               public void run() {
                   try {
                       List<MenuFoodMaterial> data=foodMaterialDao.queryForAll((Constant.FOODS_TYPE_1));
                       for(MenuFoodMaterial menuFoodMaterial:data){
                           if(TextUtils.equals(menuFoodMaterial.getId(),deviceId+menuFoodMaterial.getFoodid())){
                               stdMenuFoodMaterialList.put(menuFoodMaterial.getFoodName(),menuFoodMaterial);
                           }else {
                               foodMaterialDao.delete(menuFoodMaterial);
                           }
                       }
                   }catch (Exception e){
                       Log.e(TAG,"initStdMenuFoodMaterial1:"+e.getMessage());
                   }
               }
           });

       }catch (Exception e){
        Log.e(TAG,"initStdMenuFoodMaterial2:"+e.getMessage());
       }
    }
}
